#!/usr/bin/env php
<?php
/**
 * cli模式下脚本执行入口
 * my --init 应用初始化
 * my [--run=指定应用目录] [m/]c/a ["b=1&d=1"|b=1 d=1]
 */
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    define('MY_RUN_DIR', __DIR__);
} else {
    if (file_exists(__DIR__ . '/../../autoload.php')) { // /vendor/myphps/myphp
        define('MY_RUN_DIR', realpath(__DIR__ . '/../../../'));
    } else {
        define('MY_RUN_DIR', __DIR__);
    }
}
$_arg = getopt('', ['run:', 'init']);
$init = isset($_arg['init']);
if ($init) { //初始化
    $_SERVER['argv'] = [];
    echo 'Run Dir: ' . MY_RUN_DIR, PHP_EOL;
} else {
    if (isset($_arg['run'])) { //myphp里会取$_SERVER['argv'][1]作为uri
        if ($_SERVER['argv'][1] == '--run') { // --run app
            unset($_SERVER['argv'][1], $_SERVER['argv'][2]);
        } else { // --run=app
            unset($_SERVER['argv'][1]);
        }
        $_SERVER['argv'] = array_values($_SERVER['argv']);
    }
}
//应用目录指定
$_app = trim($_arg['run'] ?? 'app', '/\\'); //默认 app
$_appDir = MY_RUN_DIR . '/' . $_app;
if (!$init && !is_dir($_appDir)) {
    die($_appDir . ' directory does not exist');
}
$_SERVER['IS_CLI_RUN'] = true;
define('APP_PATH', $_appDir);
define('COMMON', MY_RUN_DIR . '/common');
require MY_RUN_DIR . "/vendor/autoload.php";
if (is_file(MY_RUN_DIR . "/conf.php")) require MY_RUN_DIR . "/conf.php";
require MY_RUN_DIR . "/vendor/myphps/myphp/base.php";

myphp::Run();